package services

import (
	"cloud-navigation/global"
	"cloud-navigation/utils"
	"context"
	"crypto/md5"
	"fmt"
	"image/color"
	"math/rand"
	"strings"
	"time"

	"github.com/mojocn/base64Captcha"
)

var (
	store  = base64Captcha.DefaultMemStore
	prefix = "captcha_admin_"
)

// 生成图形验证码
func CreateCaptcha(tag string, ttl, codeLen int) (string, string, error) {
	cap := utils.Captcha{
		Module: tag,
		Length: codeLen,
		Width:  100,
		Height: 40,
	}
	code, b64s, err := cap.Create()
	// code, b64s, err := MakeCaptcha(codeLen, tag)
	if err != nil {
		return "", "", err
	}
	str := md5.Sum([]byte(code))
	key := fmt.Sprintf("%x", str)[:12]

	key += prefix
	global.App.Redis.SetNX(context.Background(), prefix+key, strings.ToLower(code), time.Duration(int64(ttl))*time.Second)
	return key, b64s, err
}

// 获取验证码
func MakeCaptcha(codeLen int, tag string) (string, string, error) {
	var driver base64Captcha.Driver
	driverDigit := &base64Captcha.DriverDigit{
		Height:   64,
		Width:    200,
		MaxSkew:  0.7,
		Length:   codeLen,
		DotCount: 80,
	}
	colorRang := color.RGBA{
		uint8(rand.Intn(60) + 200),
		uint8(rand.Intn(60) + 200),
		uint8(rand.Intn(60) + 200),
		uint8(255)}
	driverString := &base64Captcha.DriverString{
		Height:          64,
		Width:           200,
		NoiseCount:      1,
		ShowLineOptions: 5,
		Length:          codeLen,
		Source:          "0123456789bcdefgkmpqrstwxy",
		BgColor:         &colorRang,
	}
	driverMath := &base64Captcha.DriverMath{
		Height:          64,
		Width:           200,
		NoiseCount:      2,
		ShowLineOptions: 5,
		BgColor:         &colorRang,
	}
	switch tag {
	case "string":
		driver = driverString
	case "digit":
		driver = driverDigit
	case "math":
		driver = driverMath
	default:
		driver = driverString
	}
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, _, err := c.Generate()
	return id, b64s, err
}

// 验证验证码
func VerifyCaptcha(code, captcha, tag string) bool {
	// return store.Verify(code, captcha, true)
	if captcha == "" {
		return false
	}
	key := prefix + code
	res, err := global.App.Redis.Get(context.Background(), key).Result()
	if err != nil {
		return false
	}
	fmt.Println(res, captcha, code)
	return res == strings.ToLower(captcha)
}
